package com.ruoyi.system.service.admin;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.constant.CommonConstant;
import com.ruoyi.common.constant.RedisKeyConstants;
import com.ruoyi.common.core.domain.entity.admin.AdminCropDB;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.check.CropSeasonUtils;
import com.ruoyi.common.utils.sql.MyPageUtils;
import com.ruoyi.system.mapper.admin.AdminCropVarietiesMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class AdminCropService extends ServiceImpl<AdminCropVarietiesMapper, AdminCropDB> {
    @Resource
    private AdminCropVarietiesMapper adminCropVarietiesDBMapper;

    @Autowired
    private RedisCache redisCache;

    /**
     * 查询后台-作物品种
     *
     * @param id 后台-作物品种主键
     * @return 后台-作物品种
     */
    public AdminCropDB selectAdminCropDBById(Long id) {
        return adminCropVarietiesDBMapper.selectById(id);
    }

    /**
     * 查询后台-作物品种列表
     *
     * @param adminCropVarietiesDB 后台-作物品种
     * @return 后台-作物品种
     */
    public TableDataInfo selectAdminCropDBList(AdminCropDB adminCropVarietiesDB) {

        // 查询当前的所有果蔬的适宜种植状态，若是没有，则初始化
        if (!redisCache.hasKey(RedisKeyConstants.PLANTING_STATUS_KEY)) {
            boolean flag = initSuitablePlantingStatus();
            // 当前时间到今天23：59：59秒的时间差（秒）
            if (flag) {
                // 获取当前时间
                LocalDateTime now = LocalDateTime.now();
                // 构造今天的 23:59:59
                LocalDateTime endOfDay = now.toLocalDate().atTime(23, 59, 59);
                // 计算相差的秒数
                long between = ChronoUnit.SECONDS.between(now, endOfDay);
                redisCache.setCacheObject(RedisKeyConstants.PLANTING_STATUS_KEY, "", (int) between, TimeUnit.SECONDS);
            }
        }
        LambdaQueryWrapper<AdminCropDB> wrapper = new LambdaQueryWrapper<>();
        // 分类，名称。品种名称
        wrapper.like(ObjectUtils.isNotEmpty(adminCropVarietiesDB.getCropName()), AdminCropDB::getCropName, adminCropVarietiesDB.getCropName());
        wrapper.eq(ObjectUtils.isNotEmpty(adminCropVarietiesDB.getCategory()), AdminCropDB::getCategory, adminCropVarietiesDB.getCategory());
        wrapper.like(ObjectUtils.isNotEmpty(adminCropVarietiesDB.getVarietyName()), AdminCropDB::getVarietyName, adminCropVarietiesDB.getVarietyName());
        wrapper.like(ObjectUtils.isNotEmpty(adminCropVarietiesDB.getPlantingSeason()), AdminCropDB::getPlantingSeason, adminCropVarietiesDB.getPlantingSeason());
        wrapper.eq(ObjectUtils.isNotEmpty(adminCropVarietiesDB.getIsActive()), AdminCropDB::getIsActive, adminCropVarietiesDB.getIsActive());
        wrapper.eq(ObjectUtils.isNotEmpty(adminCropVarietiesDB.getPlantingStatus()), AdminCropDB::getPlantingStatus, adminCropVarietiesDB.getPlantingStatus());
        wrapper.orderByDesc(AdminCropDB::getId);
        Page<AdminCropDB> pageParam = MyPageUtils.handlePageParam();
        Page<AdminCropDB> communityAreaDBPage = adminCropVarietiesDBMapper.selectPage(pageParam, wrapper);
        return TableDataInfo.covert(communityAreaDBPage);
    }

    /**
     * 新增后台-作物品种
     *
     * @param adminCropVarietiesDB 后台-作物品种
     * @return 结果
     */
    public int insertAdminCropDB(AdminCropDB adminCropVarietiesDB) {
        redisCache.deleteObject(RedisKeyConstants.PLANTING_STATUS_KEY);
        return adminCropVarietiesDBMapper.insert(adminCropVarietiesDB);
    }

    /**
     * 修改后台-作物品种
     *
     * @param adminCropVarietiesDB 后台-作物品种
     * @return 结果
     */
    public int updateAdminCropDB(AdminCropDB adminCropVarietiesDB) {
        redisCache.deleteObject(RedisKeyConstants.PLANTING_STATUS_KEY);
        return adminCropVarietiesDBMapper.updateById(adminCropVarietiesDB);
    }

    public boolean initSuitablePlantingStatus() {
        log.info("初始化果蔬种植状态开始");
        // 获取所有的植物的id，以及事宜种植的时间范围
        LambdaQueryWrapper<AdminCropDB> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(AdminCropDB::getId, AdminCropDB::getPlantingDateRange);
        queryWrapper.eq(AdminCropDB::getIsActive, CommonConstant.CONSTANT_NUM.ONE);

        List<AdminCropDB> adminCropDBList = adminCropVarietiesDBMapper.selectList(queryWrapper);
        if (ObjectUtils.isEmpty(adminCropDBList)) {
            log.info("查询事宜种植的果蔬暂无数据查出");
            return Boolean.FALSE;
        }
        ArrayList<AdminCropDB> needUpdateList = new ArrayList<>();
        for (AdminCropDB item : adminCropDBList) {
            String plantingDateRange = item.getPlantingDateRange();
            String plantingStatus = CropSeasonUtils.checkPlantingStatus(plantingDateRange);
            AdminCropDB adminCropDB = new AdminCropDB();
            adminCropDB.setId(item.getId());
            adminCropDB.setPlantingStatus(plantingStatus);
            needUpdateList.add(adminCropDB);
        }
        updateBatchById(needUpdateList);
        log.info("初始化果蔬种植状态结束");
        return Boolean.TRUE;
    }

    public List<AdminCropDB> listAll() {
        // 获取所有
        LambdaQueryWrapper<AdminCropDB> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AdminCropDB::getIsActive, CommonConstant.CONSTANT_NUM.ONE);
        List<AdminCropDB> list = adminCropVarietiesDBMapper.selectList(queryWrapper);

        // 定义排序优先级
        Map<String, Integer> orderMap = new LinkedHashMap<>();
        orderMap.put("适宜", 1);
        orderMap.put("即将适宜", 2);
        orderMap.put("已过最佳期", 3);
        orderMap.put("未到时机", 4);
        orderMap.put("不宜种植", 5);

        list.sort(Comparator.comparing(o -> orderMap.getOrDefault(o.getPlantingStatus(), 999)));


        return list;
    }


//    /**
//     * 批量删除后台-作物品种
//     *
//     * @param ids 需要删除的后台-作物品种主键
//     * @return 结果
//     */
//    public int deleteAdminCropDBByIds(Long[] ids) {
//        return adminCropVarietiesDBMapper.deleteAdminCropVarietiesDBByIds(ids);
//    }
//
//    /**
//     * 删除后台-作物品种信息
//     *
//     * @param id 后台-作物品种主键
//     * @return 结果
//     */
//
//    public int deleteAdminCropDBById(Long id) {
//        return adminCropVarietiesDBMapper.deleteAdminCropVarietiesDBById(id);
//    }
}
